package com.phonegap.breastmilk;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.phonegap.breastmilk.R;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;

public class TabFeeding extends Activity {
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabfeeding);
        
        // event click to START TIME
        Button buttonBegin =  (Button)findViewById(R.id.buttonBegin);
        buttonBegin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				beginTime(v);
			}
		});
        
        // event click to END TIME
        Button buttonEnd =  (Button)findViewById(R.id.buttonEnd);
        buttonEnd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				endTime(v);
			}
		});
        
        Button buttonSave = (Button)findViewById(R.id.buttonSave);
        buttonSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				save(v);
			}
		});
        
        final RadioGroup rg = (RadioGroup)findViewById(R.id.radioGroupButton);
        
        rg.setOnCheckedChangeListener(
            new RadioGroup.OnCheckedChangeListener() {
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                	RadioButton rb = (RadioButton)findViewById(R.id.radioButtonLeft);
                	if (rb.getId() == checkedId) {
                		rb.setTextColor(Color.WHITE);
                	} else {
                		rb.setTextColor(Color.GRAY);
                	}
                	
                	rb = (RadioButton)findViewById(R.id.radioButtonRight);
                	if (rb.getId() == checkedId) {
                		rb.setTextColor(Color.WHITE);
                	} else {
                		rb.setTextColor(Color.GRAY);
                	}
                	
                	rb = (RadioButton)findViewById(R.id.radioButtonBoth);
                	if (rb.getId() == checkedId) {
                		rb.setTextColor(Color.WHITE);
                	} else {
                		rb.setTextColor(Color.GRAY);
                	}
                }
        });
        
        
	}
	
	public void beginTime(View v) {
    	final Calendar cal = Calendar.getInstance();
    	TextView textViewBeginTime = (TextView)findViewById(R.id.textViewBeginTime);
    	
    	cal.setTimeInMillis(System.currentTimeMillis());
    	SimpleDateFormat displayTime = new SimpleDateFormat("HH:mm:ss a");
    	
    	textViewBeginTime.setText(displayTime.format(cal.getTime()));
    }
    
    public void endTime(View v) {
    	final Calendar cal = Calendar.getInstance();
    	TextView textViewEndTime = (TextView)findViewById(R.id.textViewEndTime);
    	
    	cal.setTimeInMillis(System.currentTimeMillis());
    	SimpleDateFormat displayTime = new SimpleDateFormat("HH:mm:ss a");
    	
    	textViewEndTime.setText(displayTime.format(cal.getTime()));
    }
    
    /**
     * Save item
     * @param v
     */
    public void save(View v) {
    	if (!isValidTime()) {
    		return;
    	}
    	
        SQLiteDatabase db = Connection.getInstance(this).getWritableDatabase();
        if(db != null) {
        	ContentValues nuevoRegistro = new ContentValues();
        	TextView textViewBeginTime = (TextView)findViewById(R.id.textViewBeginTime);
        	TextView textViewEndTime = (TextView)findViewById(R.id.textViewEndTime);
        	
        	// get date begin time
        	final Calendar cal = Calendar.getInstance();
        	Pattern p = Pattern.compile("([0-9]+):([0-9]+):([0-9]+)\\s[A-M]*");
    		Matcher m = p.matcher(textViewBeginTime.getText());
    		if (m.find()) {
    			cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(1)) );
    			cal.set( Calendar.MINUTE, Integer.parseInt(m.group(2)) );
            	cal.set( Calendar.SECOND, Integer.parseInt(m.group(3)) );
    		}
    		nuevoRegistro.put("date_begin", cal.getTime().toString());
    		// get date end time
    		m = p.matcher(textViewEndTime.getText());
    		if (m.find()) {
    			cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(1)) );
    			cal.set( Calendar.MINUTE, Integer.parseInt(m.group(2)) );
            	cal.set( Calendar.SECOND, Integer.parseInt(m.group(3)) );
    		}
        	nuevoRegistro.put("date_end", cal.getTime().toString());
        	
        	EditText editText = (EditText)findViewById(R.id.editTextAreaNotes);
        	nuevoRegistro.put("notes",editText.getText().toString());
        	
        	RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroupButton);
        	int rButtonId = radioGroup.getCheckedRadioButtonId();
        	RadioButton radioButtonChecked = (RadioButton)findViewById(rButtonId);
        	nuevoRegistro.put("breast_fed",radioButtonChecked.getText().toString());
        	
        	db.insert(BreastmilkSQLiteHelper.DATABASE, null, nuevoRegistro);
        	String[] from = new String [] {BreastmilkSQLiteHelper.ID,BreastmilkSQLiteHelper.DATE_BEGIN,BreastmilkSQLiteHelper.DATE_END,BreastmilkSQLiteHelper.BREAST_FED,BreastmilkSQLiteHelper.NOTES};
        	Cursor cursor = db.query(
        			BreastmilkSQLiteHelper.DATABASE, 
        			from,
        			null, null, null, null, null);
        	startManagingCursor(cursor);
        	cursor.moveToFirst();
        	AdapterJournal adapterJournal = AdapterJournal.getInstance(this, cursor, from);
        	
        	adapterJournal.changeCursor(cursor);
            //Cerramos la base de datos
            db.close();
            
            TabHost tabHost = AndroidTabsActivity.self.getTabHost();
            tabHost.setCurrentTab(1);
        }
    }
    
    /**
     * Valid time befere to save
     * @return
     */
	public boolean isValidTime() {
		TextView textViewBeginTime = (TextView)findViewById(R.id.textViewBeginTime);
    	TextView textViewEndTime = (TextView)findViewById(R.id.textViewEndTime);
    	
    	Pattern p = Pattern.compile("[0-9]+:[0-9]+:[0-9]+\\s+[A-M]*");
		Matcher m1 = p.matcher(textViewBeginTime.getText());
		Matcher m2 = p.matcher(textViewEndTime.getText());
		
		if (m1.find() && m2.find()) {
			return true;
		} else {
			return false;
		}
	}
}
